package com.sch.wanandroid.ui.main.squrare

import android.os.Bundle
import android.view.*
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.coder.zzq.smartshow.toast.SmartToast
import com.sch.wanandroid.R
import com.sch.wanandroid.adapter.ArticleAdapter
import com.sch.wanandroid.base.LazyFragment
import com.sch.wanandroid.constants.Constants
import com.sch.wanandroid.databinding.FragmentRefreshListBinding
import com.sch.wanandroid.entity.ArticleBean
import com.sch.wanandroid.ui.addshare.AddShareActivity
import com.sch.wanandroid.ui.web.WebActivity
import com.sch.wanandroid.util.AppManager
import kotlinx.android.synthetic.main.fragment_refresh_list.*

/**
 * 广场
 */

class SquareFragment : LazyFragment() {
    companion object {
        fun getInstance(): SquareFragment = SquareFragment()
    }

    private lateinit var squareViewModel: SquareViewModel
    private lateinit var databinding: FragmentRefreshListBinding

    private val articleAdapter by lazy { ArticleAdapter() }
    private var pageNum = 0
    val articleList by lazy { mutableListOf<ArticleBean>() }

    private var collectPosition = 0

    /**
     * 点击收藏后将点击事件上锁,等接口有相应结果再解锁
     * 避免重复点击产生的bug  false表示没锁，true表示锁住
     */
    private var lockCollectClick = false

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        setHasOptionsMenu(true)
        squareViewModel = ViewModelProvider(this).get(SquareViewModel::class.java)
        databinding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_refresh_list, container, false)
        databinding.lifecycleOwner = this
        return databinding.root
    }

    override fun lazyInit() {
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = articleAdapter
        recyclerView.overScrollMode = RecyclerView.OVER_SCROLL_NEVER//取消滑动到顶部边界越界效果
        initListener()
        //加载中动画
        loadingTip.loading()
        loadData()
        squareViewModel.articleListLiveData.observe(this, Observer {
            setData(it)
        })
        squareViewModel.collectSuccess.observe(this, Observer {
            collectSuccess()
        })
        squareViewModel.uncollectSuccess.observe(this, Observer {
            unCollectSuccess()
        })
    }

    private fun loadData() {
        articleList.clear()
        articleAdapter.setList(articleList)
        pageNum = 0
        squareViewModel.getArticleData(pageNum)
    }

    private fun setData(list: List<ArticleBean>) {
        dismissRefresh()
        if (list.isNotEmpty()) {
            articleList.addAll(list)
            articleAdapter.setList(articleList)
        } else {
            if (articleList.size == 0) loadingTip.showEmpty()
            else SmartToast.info("没有更多数据了")
        }
    }

    private fun initListener() {
        // 设置无网络时重新加载点击事件
        loadingTip.setReloadListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                loadingTip.loading()
                loadData()
            }
        })
        //下拉监听
        smartRefresh.setOnRefreshListener {
            loadData()
        }
        smartRefresh.setOnLoadMoreListener {
            pageNum++
            squareViewModel.getArticleData(pageNum)
        }
        articleAdapter.setOnItemClickListener { adapter, view, position ->
            intent(Bundle().apply {
                putString(Constants.WEB_URL, articleList[position].link)
                putString(Constants.WEB_TITLE, articleList[position].title)
            }, WebActivity::class.java, false)
        }
        articleAdapter.addChildClickViewIds(R.id.ivCollect)
        articleAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.ivCollect) {
                if (!AppManager.isLogin()) {
                    SmartToast.show("请先登录")
                    return@setOnItemChildClickListener
                }
                if (position < articleList.size && !lockCollectClick) {
                    lockCollectClick = true
                    collectPosition = position
                    articleList[position].apply {
                        if (collect) {
                            squareViewModel.unCollect(id)
                        } else {
                            squareViewModel.collect(id)
                        }
                    }
                }
            }
        }
    }

    fun onError(ex: String) {
        lockCollectClick = false
        //请求失败将page -1
        if (pageNum > 0) pageNum--
        dismissRefresh()
        if (articleList.size == 0) {
            loadingTip.showInternetError()
        }
        SmartToast.error(ex)
    }

    fun collectSuccess() {
        lockCollectClick = false
        if (collectPosition < articleList.size) {
            articleList[collectPosition].collect = true
            articleAdapter.setData(collectPosition, articleList[collectPosition])
        }
    }

    fun unCollectSuccess() {
        lockCollectClick = false
        if (collectPosition < articleList.size) {
            articleList[collectPosition].collect = false
            articleAdapter.setData(collectPosition, articleList[collectPosition])
        }
    }

    /**
     * 隐藏刷新加载
     */
    private fun dismissRefresh() {
        loadingTip.dismiss()
        if (smartRefresh.state.isOpening) {
            smartRefresh.finishLoadMore()
            smartRefresh.finishRefresh()
        }
    }


    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.menu_square, menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.action_add -> {
                intent(AddShareActivity::class.java, true)
            }
        }
        return super.onOptionsItemSelected(item)
    }

    fun scrollToTop() {
        recyclerView.run {
            smoothScrollToPosition(0)
        }
    }
}